<!--出库管理列表页面-->
<template>
  <div class="app-container">
    <el-form ref="form" inline :model="form" class="form-options" label-width="100px">
      <el-form-item label="单号/器材名称">
        <el-autocomplete
          ref="keywordRef"
          v-model="form.keyword"
          :fetch-suggestions="querySearchPurchaseNo"
          :trigger-on-focus="false"
          clearable
          @select="handleSelectPurchaseNo"
          @clear="clickClearkeywordRef"/>
      </el-form-item>
      <el-form-item label="仓库">
        <el-autocomplete
          ref="warehouseNameRef"
          v-model="form.warehouseName"
          :fetch-suggestions="querySearchBatchNo"
          :trigger-on-focus="false"
          clearable
          @select="handleSelectBatchNo"
          @clear="clickClearwarehouseNameRef"/>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="form.status" filterable clearable>
          <el-option
            v-for="item in statusOptions"
            :key="item.valueId"
            :label="item.valueName"
            :value="item.valueId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="出库完成时间" class="long-content">
        <el-date-picker
          v-model="form.date"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          align="right">
        </el-date-picker>
      </el-form-item>
      <div class="btns">
        <el-button type="primary" v-permission="['out_manage_add']" @click="onAdd">新增</el-button>
        <el-button type="primary" v-permission="['out_manage_query']" @click="onQuery">查询</el-button>
      </div>
    </el-form>
    <el-table
      :data="tableData"
      header-cell-class-name="table-header"
      style="width: 100%;margin-top: 20px">
      <el-table-column
        label="序号"
        type="index"
        width="50">
      </el-table-column>
      <el-table-column
        prop="outNo"
        label="出库单号">
      </el-table-column>
      <el-table-column
        prop="outExplain"
        label="出库说明">
      </el-table-column>
      <el-table-column
        prop="warehouseName"
        label="出库仓库">
      </el-table-column>
      <el-table-column
        prop="targetLocationName"
        label="目标位置">
      </el-table-column>
      <el-table-column
        prop="statusName"
        label="状态">
      </el-table-column>
      <el-table-column
        prop="outTime"
        label="出库完成时间">
      </el-table-column>
      <el-table-column
        prop="operName"
        label="操作人">
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="操作时间">
      </el-table-column>
      <el-table-column label="操作" width="220px">
        <template slot-scope='scope'>
          <el-button type="primary" v-permission="['out_manage_show']" @click="handleOperateClick(scope.row,'查看')">查看
          </el-button>
          <el-button type="primary" v-permission="['out_manage_edit']" v-if="scope.row.status==0" @click="handleOperateClick(scope.row,'修改')">修改
          </el-button>
          <el-button type="primary" v-permission="['out_manage_returnQuery']" v-if="scope.row.status==3" @click="handleOperateClick(scope.row,'还库')">还库
          </el-button>
          <el-button type="danger" v-permission="['out_manage_del']" v-if="scope.row.status==0" @click="handleOperateClick(scope.row,'删除')">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="text-align: right;margin-top: 20px">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 15, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <el-dialog
      :title="dialogTitle"
      top="25px"
      v-if="dialogVisible"
      :visible.sync="dialogVisible"
      width="1300px">
      <WarehouseExComponent
        @onSave="onSave"
        :type="warehouseExType"
        @onSubmit="onSubmit"
        :form="dataForm"
        ref="WarehouseExComponent"/>
      <span slot="footer">
            <el-button type="primary" v-if="warehouseExType>=1" @click="addEquipment()">添加器材</el-button>
            <el-button type="primary" v-if="warehouseExType>=1" @click="saveData()">保存</el-button>
            <el-button type="primary" v-if="warehouseExType>=1" @click="submitData()">保存并提交</el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
          </span>
    </el-dialog>

    <el-dialog
      title="出库归还"
      top="25px"
      v-if="returnDialogVisible"
      :visible.sync="returnDialogVisible"
      width="1300px">
      <WarehouseReturnComponent
        @onSubmitReturn="onSubmitReturn"
        :id="returnDataId"
        @onShowSubmit="onShowSubmit"
        ref="WarehouseReturnComponent"/>
      <span slot="footer">
            <el-button type="primary" v-permission="['out_manage_returnAdd']" v-if="showSubmit" @click="submitReturnData">提交</el-button>
            <el-button @click="returnDialogVisible = false">取消</el-button>
          </span>
    </el-dialog>
  </div>
</template>

<script>
import { getTypes } from '@/api/common'
import WarehouseExComponent from '../components/WarehouseExComponent'
import WarehouseReturnComponent from '../components/WarehouseReturnComponent'
import { getIdsFromTreeData } from '@/utils/public'
import {
  getBaseEquipmentType,
  delWarehouseEx,
  getWarehouseExList,
  getWarehouseExNo,
  getWarehouse
} from '@/api/warehouse'

export default {
  name: 'WarehouseEx',
  components: {
    WarehouseExComponent,
    WarehouseReturnComponent
  },
  data() {
    return {
      currentPage: 1,
      total: 0,
      pageSize: 10,
      form: {
        date: '',
        beginTime: '',
        endTime: '',
        outNo: '',
        keyword: '',
        warehouseId: '',
        warehouseName: '',
        status: ''
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      loading: false,
      tableData: [],
      dialogVisible: false,
      dialogTitle: '新增出库',
      returnDialogVisible: false,
      purchaseOptions: [],
      statusOptions: [],
      warehouseExType: 2,
      dataForm: {},
      returnDataId: '',
      warehouseOptions: [],
      showSubmit: false
    }
  },
  created() {
    getTypes({ typeId: 'order_out_status' }).then(res => {
      this.statusOptions = res.resultData
    })

    getWarehouse({}).then(res => {
      this.warehouseOptions = res.resultData
    })
    this.onQuery()
  },
  methods: {
    handleSizeChange: function(val) {
      this.pageSize = val
      this.currentPage = 1
      this.getTableData()
    },
    handleCurrentChange: function(val) {
      this.currentPage = val
      this.getTableData()
    },
    handleOperateClick(row, tag) {
      if (tag == '删除') {
        this.$confirm('确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          delWarehouseEx({ id: row.id }).then(res => {
            this.onQuery()
          })
        })
      } else if (tag == '查看') {
        this.dialogTitle = '查看出库'
        this.queryDetail(row.id, true)
      } else if (tag == '修改') {
        this.dialogTitle = '编辑出库'
        this.queryDetail(row.id, false)
      } else if (tag == '还库') {
        this.returnDataId = row.id
        this.returnDialogVisible = true
      }
    },
    queryDetail(id, isReadOnly) {
      const param = { page: 1, rows: 1, id: id }
      const a = new Promise(resolve => {
        getBaseEquipmentType({}).then(res => {
          resolve(res.resultData)
        })
      })

      const b = new Promise(resolve => {
        getWarehouseExList(param).then(res => {
          resolve(res.resultData[0])
        })
      })

      Promise.all([a, b]).then(res => {
        const treeData = res[0]
        const data = res[1]
        this.dataForm = {
          id: data.id,
          outNo: data.outNo,
          outExplain: data.outExplain,
          status: data.status,
          warehouseId: data.warehouseId,
          outTime: data.outTime,
          operName: data.operName,
          operId: data.operId,
          operTime: data.createTime,
          targetLocation: data.targetLocation,
          busOutDetailsList: []
        }
        data.busOutDetailsList.forEach(item => {
          const array = []
          getIdsFromTreeData(item.equipmentTypeId, treeData, array)
          item.equipmentTypeId = array
          this.dataForm.busOutDetailsList.push(item)
        })
        this.warehouseExType = isReadOnly ? 0 : 1
        this.dialogVisible = true
      })
    },
    querySearchBatchNo: function(queryString, cb) {
      // 调用 callback 返回建议列表的数据
      const results = []
      cb(results)
    },
    handleSelectBatchNo(item) {
      // console.log(item)
    },
    querySearchPurchaseNo: function(queryString, cb) {
      // 调用 callback 返回建议列表的数据
      const results = []
      cb(results)
    },
    handleSelectPurchaseNo(item) {
      console.log(item)
    },
    clickClearkeywordRef(){
      this.$nextTick(() => {
        if (this.$refs.keywordRef) {
          this.$refs.keywordRef.activated = true;
        }
      });
    },
    clickClearwarehouseNameRef(){
      this.$nextTick(() => {
        if (this.$refs.warehouseNameRef) {
          this.$refs.warehouseNameRef.activated = true;
        }
      });
    },
    handleSelectOperName(item) {
      this.form.operName = item.value
    },
    handleSelectPurchaseName(item) {
      this.form.purchaseName = item.value
    },
    getTableData() {
      if (this.form.date && this.form.date[0]) {
        this.form.beginTime = this.form.date[0]
      } else {
        this.form.beginTime = ''
      }
      if (this.form.date && this.form.date[1]) {
        this.form.endTime = this.form.date[1]
      } else {
        this.form.endTime = ''
      }
      const param = { page: this.currentPage, rows: this.pageSize }
      Object.assign(param, this.form)
      getWarehouseExList(param).then(res => {
        this.tableData = res.resultData
        this.total = res.total
      })
    },
    addEquipment() {
      this.$refs['WarehouseExComponent'].addEquipment()
    },
    saveData() {
      this.$refs['WarehouseExComponent'].save()
    },
    onSave() {
      this.dialogVisible = false
      this.onQuery()
    },
    submitData() {
      this.$refs['WarehouseExComponent'].saveAndSubmit()
    },
    onSubmit() {
      this.dialogVisible = false
      this.onQuery()
    },
    submitReturnData() {
      this.$refs['WarehouseReturnComponent'].saveAndSubmit()
    },
    onSubmitReturn() {
      this.$message({ type: 'success', message: '提交成功！' })
      this.returnDialogVisible = false
      this.onQuery()
    },
    onShowSubmit(e) {
      this.showSubmit = e
    },
    onQuery() {
      this.currentPage = 1
      this.getTableData()
    },
    onAdd() {
      getWarehouseExNo({}).then(res => {
        this.dataForm = {
          outNo: res.resultData,
          outExplain: '',
          status: 0,
          warehouseId: '',
          outTime: '',
          operName: '',
          operId: '',
          operTime: '',
          targetLocation: '',
          busOutDetailsList: []
        }
        this.dialogTitle = '新增出库'
        this.warehouseExType = 2
        this.dialogVisible = true
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.line {
  text-align: center;
}
</style>

